// js/game.js

let board;
let currentPiece;
let nextPiece;
let score;
let level;
let linesCleared;
let gameLoopInterval;
let isGameOver;
let currentSpeed;

// 创建空的游戏区域
function createEmptyBoard() {
    return Array.from({ length: ROWS }, () => Array(COLS).fill(0));
}

// 生成随机方块
function getRandomPiece() {
    const randIndex = Math.floor(Math.random() * (SHAPES.length - 1)) + 1; // 1 到 SHAPES.length - 1
    const shape = SHAPES[randIndex];
    const colorIndex = shape.flat().find(val => val > 0) || randIndex; // 找到形状中的非零值作为颜色索引

    // 初始位置 (顶部中间)
    const x = Math.floor(COLS / 2) - Math.ceil(shape[0].length / 2);
    const y = 0; // 从顶部开始

    return {
        x: x,
        y: y,
        shape: shape,
        colorIndex: colorIndex // 存储颜色索引，方便绘制
    };
}

// 检查移动是否有效 (边界碰撞和方块碰撞)
function isValidMove(piece, board) {
    for (let y = 0; y < piece.shape.length; y++) {
        for (let x = 0; x < piece.shape[y].length; x++) {
            if (piece.shape[y][x] > 0) { // 只检查方块实体部分
                const boardX = piece.x + x;
                const boardY = piece.y + y;

                // 检查边界
                if (boardX < 0 || boardX >= COLS || boardY >= ROWS) {
                    return false;
                }
                // 检查是否碰到下方已固定的方块 (注意 boardY 可能为负数，需要跳过)
                if (boardY >= 0 && board[boardY] && board[boardY][boardX] > 0) {
                    return false;
                }
            }
        }
    }
    return true;
}

// 旋转方块 (顺时针)
function rotate(piece) {
    const N = piece.shape.length;
    const newShape = Array.from({ length: N }, () => Array(N).fill(0));

    for (let y = 0; y < N; y++) {
        for (let x = 0; x < N; x++) {
            newShape[x][N - 1 - y] = piece.shape[y][x];
        }
    }
    return newShape;
}

// 尝试旋转当前方块
function tryRotate() {
    if (isGameOver) return;
    const originalShape = currentPiece.shape;
    const rotatedShape = rotate(currentPiece);
    const testPiece = { ...currentPiece, shape: rotatedShape };

    // 简单的碰撞检测，没有实现 wall kick
    if (isValidMove(testPiece, board)) {
        currentPiece.shape = rotatedShape;
    } else {
        // 尝试左右移动一点来适应旋转 (简单 wall kick 模拟)
        // 尝试右移 1 格
        testPiece.x++;
        if (isValidMove(testPiece, board)) {
            currentPiece.shape = rotatedShape;
            currentPiece.x++;
            return;
        }
        // 尝试左移 1 格
        testPiece.x -= 2; // 从原始位置左移 1 格
         if (isValidMove(testPiece, board)) {
            currentPiece.shape = rotatedShape;
            currentPiece.x--;
            return;
        }
         // 如果是 I 形块，尝试移动更多
         if (originalShape.length > 2) { // 假设 I 形块是 4x4
             testPiece.x++; // 回到原始 x
             testPiece.x -= 2; // 尝试左移 2 格
             if (isValidMove(testPiece, board)) {
                 currentPiece.shape = rotatedShape;
                 currentPiece.x -= 2;
                 return;
             }
             testPiece.x += 4; // 尝试右移 2 格
             if (isValidMove(testPiece, board)) {
                 currentPiece.shape = rotatedShape;
                 currentPiece.x += 2;
                 return;
             }
         }
        // 旋转失败
    }
}


// 尝试移动当前方块
function tryMove(dx, dy) {
    if (isGameOver) return false;
    const testPiece = { ...currentPiece, x: currentPiece.x + dx, y: currentPiece.y + dy };
    if (isValidMove(testPiece, board)) {
        currentPiece.x += dx;
        currentPiece.y += dy;
        return true; // 移动成功
    }
    return false; // 移动失败 (碰撞)
}

// 瞬间下落 (Hard Drop)
function hardDrop() {
    if (isGameOver) return;
    while (tryMove(0, 1)) {
        // 持续向下移动直到碰撞
        // 可选：增加硬下落得分
        // score += POINTS.HARD_DROP;
    }
    // 移动完成后，立即锁定并处理后续逻辑
    lockPiece();
    handlePostLock();
}


// 将当前方块固定到游戏区域
function lockPiece() {
    currentPiece.shape.forEach((row, y) => {
        row.forEach((value, x) => {
            if (value > 0) {
                const boardX = currentPiece.x + x;
                const boardY = currentPiece.y + y;
                // 防止方块锁定在屏幕上方区域外 (虽然理论上不应发生)
                if (boardY >= 0 && boardY < ROWS && boardX >= 0 && boardX < COLS) {
                    board[boardY][boardX] = currentPiece.colorIndex;
                }
            }
        });
    });
}

// 检查并清除满行
function clearLines() {
    let linesClearedCount = 0;
    for (let y = ROWS - 1; y >= 0; y--) {
        if (board[y].every(cell => cell > 0)) {
            // 该行已满
            linesClearedCount++;
            // 将该行上面的所有行向下移动一行
            for (let row = y; row > 0; row--) {
                board[row] = board[row - 1];
            }
            // 最顶行填充为空白
            board[0] = Array(COLS).fill(0);
            // 因为删了一行，需要重新检查当前行 (y 不变)
            y++; // 抵消外层循环的 y--
        }
    }
    return linesClearedCount;
}

// 更新分数和等级
function updateScoreAndLevel(clearedCount) {
    if (clearedCount > 0) {
        let lineScore = 0;
        switch (clearedCount) {
            case 1: lineScore = POINTS.SINGLE; break;
            case 2: lineScore = POINTS.DOUBLE; break;
            case 3: lineScore = POINTS.TRIPLE; break;
            case 4: lineScore = POINTS.TETRIS; break;
        }
        score += lineScore * level; // 分数乘以当前等级
        linesCleared += clearedCount;

        // 检查是否升级
        const newLevel = Math.floor(score / LEVEL_THRESHOLD) + 1;
        if (newLevel > level) {
            level = newLevel;
            // 加快速度
            currentSpeed = Math.max(MIN_SPEED, INITIAL_SPEED - (level - 1) * SPEED_INCREMENT);
            // 重置游戏循环计时器
            if (gameLoopInterval) {
                clearInterval(gameLoopInterval);
                gameLoopInterval = setInterval(gameLoop, currentSpeed);
            }
            updateLevelDisplay(level);
        }
        updateScoreDisplay(score);
    }
}

// 处理方块锁定后的逻辑：清行、计分、生成新块、检查游戏结束
function handlePostLock() {
    const clearedCount = clearLines();
    updateScoreAndLevel(clearedCount);

    // 生成下一个方块
    currentPiece = nextPiece;
    nextPiece = getRandomPiece();
    drawNextPiece(nextPiece); // 更新预览

    // 检查新生成的方块是否立即碰撞，如果是则游戏结束
    if (!isValidMove(currentPiece, board)) {
        isGameOver = true;
        clearInterval(gameLoopInterval);
        gameLoopInterval = null; // 清除引用
        console.log("Game Over!");
        showGameOverModal(score);
        startButton.textContent = "重新开始"; // 更新按钮文本
        startButton.disabled = false; // 使按钮可用
    }
}

// 游戏主循环
function gameLoop() {
    if (isGameOver) return;

    // 尝试向下移动
    const moved = tryMove(0, 1);

    if (!moved) {
        // 如果向下移动失败 (碰到障碍或底部)
        lockPiece();
        handlePostLock();
    }

    // 无论是否移动成功，都重绘界面
    if (!isGameOver) { // 确保游戏未在 handlePostLock 中结束
        clearCanvas(ctx, canvas);
        drawBoard(board);
        drawPiece(currentPiece);
    }
}

// 开始新游戏
function startGame() {
    // 初始化状态
    board = createEmptyBoard();
    score = 0;
    level = 1;
    linesCleared = 0;
    isGameOver = false;
    currentSpeed = INITIAL_SPEED;

    // 获取初始方块
    currentPiece = getRandomPiece();
    nextPiece = getRandomPiece();

    // 更新界面显示
    updateScoreDisplay(score);
    updateLevelDisplay(level);
    clearCanvas(ctx, canvas); // 清空主画布
    drawNextPiece(nextPiece); // 显示第一个 "下一个" 方块
    hideGameOverModal(); // 确保游戏结束弹窗是隐藏的
    hideLeaderboardModal(); // 确保排行榜弹窗是隐藏的
    setStatusMessage(statusMessageElement, ''); // 清空状态消息

    // 启动游戏循环
    if (gameLoopInterval) {
        clearInterval(gameLoopInterval);
    }
    gameLoopInterval = setInterval(gameLoop, currentSpeed);

    console.log("Game started!");
    startButton.textContent = "游戏中..."; // 或 "暂停" 如果实现暂停功能
    startButton.disabled = true; // 游戏进行中禁用开始按钮
}

// 处理键盘输入
function handleInput(event) {
    if (isGameOver || !currentPiece) return; // 游戏结束或方块未初始化时忽略输入

    switch (event.key) {
        case KEY.LEFT:
            tryMove(-1, 0);
            // 移动后立即重绘，提供即时反馈
            clearCanvas(ctx, canvas);
            drawBoard(board);
            drawPiece(currentPiece);
            break;
        case KEY.RIGHT:
            tryMove(1, 0);
            clearCanvas(ctx, canvas);
            drawBoard(board);
            drawPiece(currentPiece);
            break;
        case KEY.DOWN:
            // 加速下落 (Soft Drop)
            const moved = tryMove(0, 1);
            if (moved) {
                // 可选：增加软下落得分
                // score += POINTS.SOFT_DROP;
                // updateScoreDisplay(score);
                // 加速下落后也重绘
                clearCanvas(ctx, canvas);
                drawBoard(board);
                drawPiece(currentPiece);
            } else {
                // 如果软下落到底，直接锁定 (可选，或者等下一次 gameLoop 自动锁定)
                // lockPiece();
                // handlePostLock();
            }
            break;
        case KEY.UP:
            // 旋转
            tryRotate();
            clearCanvas(ctx, canvas);
            drawBoard(board);
            drawPiece(currentPiece);
            break;
        case KEY.SPACE: // 硬下落
             event.preventDefault(); // 防止空格键触发页面滚动或按钮点击
             hardDrop();
             // hardDrop 内部会处理绘图和后续逻辑
             break;
        // case KEY.P: // 暂停/恢复 (需要额外逻辑)
        //     togglePause();
        //     break;
    }
}